﻿using System;

using ComponentFactory.Krypton.Toolkit;

using ExtensibleEventViewer.Console.DomainModel;


namespace ExtensibleEventViewer.Console.Controls
{
	public partial class TimePeriodControl : DecoratedUserControl
	{
		private const string SECOND_SHORT = "sec";
		private const string MINUTE_SHORT = "min";

		private bool isValid;

		public TimePeriodControl()
		{
			InitializeComponent();
		}

		private int SelectedTimePeriodValue
		{
			get
			{
				return (int)ddlTimePeriodValue.Value;
			}
			set
			{
				ddlTimePeriodValue.Value = value;
			}
		}

		private TimePeriodUnit SelectedTimePeriodUnit
		{
			get
			{
				switch ((string)ddlTimePeriodUnit.SelectedItem)
				{
					case MINUTE_SHORT:
						return TimePeriodUnit.Minutes;
					case SECOND_SHORT:	
					default:
						return TimePeriodUnit.Seconds;
				}
			}
			set
			{
				switch (value)
				{
					case TimePeriodUnit.Minutes:
						ddlTimePeriodUnit.SelectedItem = MINUTE_SHORT;
						break;
					case TimePeriodUnit.Seconds:
					default:
						ddlTimePeriodUnit.SelectedItem = SECOND_SHORT;
						break;
				}
			}
		}

		public void InvalidateTimePeriod()
		{
			ddlTimePeriodValue.Palette = ERROR_STATE_PALETTE;

			isValid = false;
		}

		public TimeSpan TimePeriod
		{
			get
			{
				TimeSpan timeSpan = new TimeSpan(
					0,
					SelectedTimePeriodUnit == TimePeriodUnit.Minutes ? SelectedTimePeriodValue : 0,
					SelectedTimePeriodUnit == TimePeriodUnit.Seconds ? SelectedTimePeriodValue : 0);

				return timeSpan;
			}
			set
			{
				if(value.TotalMinutes >= 2)
				{
					SelectedTimePeriodValue = (int)value.TotalMinutes;
					SelectedTimePeriodUnit = TimePeriodUnit.Minutes;
				}
				else
				{
					SelectedTimePeriodValue = (int)value.TotalSeconds;
					SelectedTimePeriodUnit = TimePeriodUnit.Seconds;
				}
			}
		}

		private void TimePeriodValueChanged(object sender, EventArgs e)
		{
			if (!isValid)
			{
				ddlTimePeriodValue.ResetPalette();

				isValid = true;
			}
		}

		public override PaletteMode PaletteMode
		{
			set
			{
				ddlTimePeriodUnit.PaletteMode = ddlTimePeriodValue.PaletteMode = value;
			}
		}
	}
}
